/*
 * #depends player-controller.js
 */
Ext.ns('Ext.ux.mattgoldspink.subsonic.Util');

Ext.ux.mattgoldspink.subsonic.Util.renderTime = function(time){
    return Ext.util.Format.number((time / 60), '0') + ':' + Ext.util.Format.number((time % 60)/100, '.00').substring(2);
};

Ext.ux.mattgoldspink.subsonic.Display = Ext.extend(Ext.Container, {
    display: undefined,
    currentTrackTpl: new Ext.XTemplate(
        '<div class="current-track">',
            '<div class="title">{title}</div>',
            '<div class="scroller-container">',
            '<div class="artist">{artist} &mdash; {album}</div>',
            '</div>',
            '<div class="current-position">',
            '<div class="current-time">0:00</div>',
            '<div class="position"></div>',
            '<div class="remaining-time">-{[Ext.ux.mattgoldspink.subsonic.Util.renderTime(values.duration)]}</div>',
            '</div>',
        '</div>'
    ),
    emptyDisplay: function(){
        this.display.update('<img class="logo" src="'+Ext.BLANK_IMAGE_URL +'" />');
    },
    setProgress: function(subject, progress){
        progress = progress/1000;
        this.display.child('.current-time').update(Ext.ux.mattgoldspink.subsonic.Util.renderTime(progress));
        this.display.child('.remaining-time').update(Ext.ux.mattgoldspink.subsonic.Util.renderTime(this.slider.maxValue - progress));
        this.slider.setValue(progress, true);
    },
    showTrack: function(track){
        Ext.destroy(this.slider);
        this.display.update(this.currentTrackTpl.applyTemplate(track));
        this.slider = new Ext.Slider({
            renderTo: this.display.child('.position'),
                minValue: 0,
                maxValue: track.duration
        });
        this.slider.on('changecomplete', function(slider, e, thumb){
            this.publish('subsonic.player.skipto', (slider.getValue() / slider.maxValue)*100);
        }, this);
    },
    constructor: function(config) {
		Ext.apply(this, config,
			{
				html: "<div class='display'></div>",
				flex: 1,
				height: 50,
				cls: 'display-wrapper',
				plugins: ['msgbus']
			}
		);
		Ext.ux.mattgoldspink.subsonic.Display.superclass.constructor.apply(this, arguments);
		this.on('afterrender', function(){
			this.display = this.getEl().child('.display');
			this.display.boxWrap();
			this.emptyDisplay();
		}, this);
		this.subscribe('subsonic.track.nowplaying', {
			fn: function(topic, track){
				this.showTrack(track);
			},
			scope: this
		});
		this.subscribe('subsonic.track.paused', {
			fn: function(topic, track){
				this.showTrack(track);
			},
			scope: this
		});
		this.subscribe('subsonic.track.stopped', {
			fn: function(topic, track){
				this.emptyDisplay();
			},
			scope: this
		});
		this.subscribe('subsonic.track.whileplaying', {
			fn: this.setProgress,
			scope: this
		});
    }
});

Ext.ux.mattgoldspink.subsonic.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.ux.mattgoldspink.subsonic.SearchField.superclass.initComponent.call(this);
        this.on('keyup', function(field, event){
            if (Ext.isEmpty(field.getValue())) {
                this.triggers[1].hide();
            } else {
                Ext.get(this.triggers[1].dom).applyStyles('display: block');
            }
			this.publish('subsonic.search.store', {
				text: field.getRawValue(),
				searchType: field.getQueryType()
			});
        }, this);
    },
	plugins: ['msgbus'],
    ref: '../search',
    trigger1Class:'x-search-options-trigger',
    trigger2Class:'x-search-clear-trigger',
    width: 180,
    searchType: 'all',
    emptyText: 'Search Music',
    enableKeyEvents: true,
    hideTrigger2:true,
    onItemCheck : function(item, checked) {
        if (checked === true) {
            this.searchType = item.searchType;
            this.fireEvent('keyup', this);
        }
    },
    makeAndShowMenu: function(){
        if (this.menu === undefined){
            this.menu = new Ext.menu.Menu({
				items: [
                    // stick any markup in a menu
                    '<b class="menu-title">Search</b>',
                    {
                        text: 'All',
                        searchType: 'all',
                        checked: true,
                        group: 'searchType',
                        checkHandler: this.onItemCheck,
                        scope: this
                    }, {
                        text: 'Artist',
                        searchType: 'artist',
                        checked: false,
                        group: 'searchType',
                        checkHandler: this.onItemCheck,
                        scope: this
                    }, {
                        text: 'Album',
                        searchType: 'album',
                        checked: false,
                        group: 'searchType',
                        checkHandler: this.onItemCheck,
                        scope: this
                    }, {
                        text: 'Song',
                        searchType: 'song',
                        checked: false,
                        group: 'searchType',
                        checkHandler: this.onItemCheck,
                        scope: this
                    }
                ]
            });
       }
       this.menu.show(this.getEl());
    },
    onTrigger1Click : function(){
		this.makeAndShowMenu();
    },
    onTrigger2Click : function(){
        this.el.dom.value = '';
        this.triggers[1].hide();
    },
    getQueryType: function(){
		return this.searchType; 
    }
});

Ext.ux.mattgoldspink.subsonic.PlayerPanel = Ext.extend(Ext.Panel, {
    constructor: function(config) {
        Ext.apply(this, config,
            {
                title: 'subTunes',
                plugins: ['msgbus'],
                bodyCssClass: 'subsonic-player',
                cls: 'subsonic-player',
                closable: true,
                height: 69,
                resizeable: true,
                layout: 'hbox',
                layoutConfig:{
                     padding: '0 15 0 15'   
                },
                defaults: {
            border: true
                },
                items: [
                    this.makePlayControlsContainer(),
                    this.makeVolumeSliderContainer(),
                    new Ext.ux.mattgoldspink.subsonic.Display(),
                    this.makeViewChooserContainer(),
                    this.makeSearchFieldContainer()
                ]
            }
        );
        Ext.ux.mattgoldspink.subsonic.PlayerPanel.superclass.constructor.apply(this, arguments);
        this.setupButtonSubscriptions();
        this.setupVolumeListeners();
    },
    setupVolumeListeners: function(){
		this.volume.on('drag', function(slider, e, thumb){
			this.publish('subsonic.player.volume.set', thumb.value);
        }, this);
		this.volume.on('dragstart', function(slider, e, thumb){
			this.publish('subsonic.player.volume.set', thumb.value);
        }, this);
		this.volume.on('changecomplete', function(slider, newvalue, thumb){
			this.publish('subsonic.player.volume.set', newvalue);
        }, this);
    },
    setupButtonSubscriptions: function(){
        this.subscribe('subsonic.track.nowplaying', {
            scope: this,
            fn: this.handleNowPlaying
        });
        this.subscribe('subsonic.track.paused', {
            scope: this,
            fn: this.handlePaused
        });
        this.subscribe('subsonic.track.stopped', {
            scope: this,
            fn: this.handleStopped
        });
    },
    handlePaused: function(subject, track) {
        this.backbutton.addClass('enable');
        this.forwardbutton.addClass('enable');
        this.playbutton.removeClass('enable');
        this.publish('subsonic.player.pause', true);
    },
    handleStopped: function(subject, track) {
        this.backbutton.removeClass('enable');
        this.playbutton.removeClass('enable');
        this.forwardbutton.removeClass('enable');
        this.publish('subsonic.player.stop', true);
    },
    handleNowPlaying: function(subject, track) {
        this.backbutton.addClass('enable');
        this.playbutton.addClass('enable');
        this.forwardbutton.addClass('enable');
        this.publish('subsonic.player.start', true);
    },
    makeSearchFieldContainer: function(){
        return {
            xtype: 'container',
         cls: 'search',
            width: 180,
            items: [
                new Ext.ux.mattgoldspink.subsonic.SearchField({})
        ]
        };
    },
    makeVolumeSliderContainer: function(){
        return {
            xtype: 'container',
            width: 130,
            items: [
                {
                width: 100,
                minValue: 0,
                maxValue: 100,
                value: 100,
                ref: '../volume',
                cls: 'volume',
                xtype: 'slider',
                stateful: true,
                stateId: 'subTunesVolume',
                plugins: ['msgbus'],
                stateEvents: ['dragend','click'],
                getState: function(){
                    return {value: this.getValue()};
                },
                applyState: function(state) {
                    this.setValue(state.value);
                    this.publish('subsonic.player.volume.set', state.value);
                }
            }
            ],
            listeners : {
                afterrender: function(){
                    this.volume.getEl().insertHtml('afterBegin', '<b class="volume-min"></b>');
                    this.volume.getEl().insertHtml('beforeEnd', '<b class="volume-max"></b>');
                },
                scope: this
            }
     };
    },
    makeViewChooserContainer: function(){
        return {
            ref: 'viewchooser',
            cls: 'viewchooser',
            xtype: 'container',
            width: 106,
            layout: 'hbox',
            defaults: {
                xtype: 'button',
                enableToggle: true,
                toggleGroup: 'viewchooser',
                listeners: {
                toggle: function(button, pressed) {
                    if (pressed && this.publish) {
                        this.publish('subsonic.view.change', button.initialConfig.cls);
                    }
                },
                scope: this
            },
            stateful: true,
                stateEvents: ['toggle'],
                getState: function(){
                    return {pressed: this.pressed};
                },
                applyState: function(state){
                    this.toggle(state.pressed);
                }
            },
            items: [
                {
                    iconCls: 'grid',
                    pressed: false,
                    cls: 'gridview',
                    stateId: 'gridview'
                },
                {
                    iconCls: 'album',
                    pressed: true,
                    cls: 'albumview',
                    stateId: 'albumview'
                },
                {
                    iconCls: 'coverflow',
                    pressed: false,
                    cls: 'coverflow',
                    stateId: 'coverflow'
                }
            ]
        };
    },
    makePlayControlsContainer: function(){
        return {
            ref: 'controls',
            xtype: 'container',
            plugins: ['msgbus'],
            width: 160,
            html: '<div class="control-wrapper"><div class="controls"><img src="'+Ext.BLANK_IMAGE_URL+'" class="back-button" /><img src="'+Ext.BLANK_IMAGE_URL+'" class="play-button" /><img src="'+Ext.BLANK_IMAGE_URL+'" class="forward-button" /></div></div>',
            listeners: {
                afterrender: function(){
                    this.backbutton = this.controls.getEl().child('.back-button');
                    this.playbutton = this.controls.getEl().child('.play-button');
                    this.forwardbutton = this.controls.getEl().child('.forward-button');
                    this.backbutton.on('click', function(){
                        this.publish('subsonic.player.back', true);
                    }, this);
                    this.playbutton.on('click', function(){
                        if (this.playbutton.hasClass('enable')) {
                            this.publish('subsonic.player.pause', true);
                        } else {
                            this.publish('subsonic.player.play', true);
                        }
                    }, this);
                    this.forwardbutton.on('click', function(){
                        this.publish('subsonic.player.forward', true);
                    }, this);
                },
                scope: this
            }
        };
    }
});
